package com.ios.service.impl;

import com.ios.mapper.ReservationMapper;
import com.ios.mapper.ViolationMapper;
import com.ios.model.entity.Reservation;
import com.ios.model.entity.Violation;
import com.ios.service.ViolationService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class ViolationServiceImpl implements ViolationService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ReservationMapper reservationMapper;

    @Autowired
    private ViolationMapper violationMapper;


    // 定义每次违规扣除的分数（可配置化）
    private static final int DEDUCT_SCORE_PER_VIOLATION = 5;

    /**
     * 将未签到且未处理的预约记录导入违规表
     * @return
     */

    @Override
    @Transactional
    public int importUncheckedToViolation(Integer uncheckedStatus) {
        log.info("开始导入未签到记录，状态码: {}", uncheckedStatus);

        List<Reservation> reservations = reservationMapper.selectUncheckedReservations(uncheckedStatus);
        log.info("查询到 {} 条未签到记录", reservations.size());

        // 扣分操作前置处理
        reservations.forEach(reservation -> {
            Long userId = reservation.getUserId();
            try {
                log.info("开始扣除用户 {} 的信用分", userId);
                sysUserMapper.deductCredit(userId, DEDUCT_SCORE_PER_VIOLATION);
                Long currentCredit = sysUserMapper.getUserCredit(userId);
                log.info("用户 {} 当前信用分: {}", userId, currentCredit);
            } catch (Exception e) {
                log.error("用户 {} 扣分失败: {}", userId, e.getMessage());
                throw new RuntimeException("信用分扣除失败", e);
            }
        });

        // 转换并批量插入违规记录
        List<Violation> violations = reservations.stream()
                .map(this::convertToViolation)
                .collect(Collectors.toList());

        if (!violations.isEmpty()) {
            int count = violationMapper.batchInsert(violations);
            log.info("成功插入 {} 条违规记录", count);
            return count;
        }
        return 0;
    }

    @Override
    public List<Violation> getViolationByUserId(Long id) {
        return violationMapper.getViolationByUserId(id);
    }


    @Override
    public void updateStatus(Long id, Long userId, int status) {
        log.info("更新违规状态：id={}, userId={}, status={}", id, userId, status);

        if (status == 2) {
            // 查询当前信用分
            Long currentCredit = sysUserMapper.selectUserById(userId).getCredit();
            log.info("[信用分更新] 当前信用分: userId={}, credit={}", userId, currentCredit);

            // 计算新信用分
            Long newCredit = Math.min(currentCredit + DEDUCT_SCORE_PER_VIOLATION, 100);
            log.info("[信用分更新] 计算后新信用分: {}", newCredit);

            // 执行更新并记录影响行数
            int updateRows = sysUserMapper.updateUserCredit(userId, newCredit);
            log.info("[信用分更新] 影响行数: {}", updateRows); // 关键日志！
        }

        // 更新违规记录状态
        violationMapper.updateStatus(id, status);
    }

    @Override
    @Transactional
    public void rejectUpdateStatus(Long id, Long userId) {
        try {
            log.info("驳回申诉并扣除信用分：id={}, userId={}", id, userId);

            // 参数校验
            if (id == null || userId == null) {
                throw new IllegalArgumentException("参数不能为空");
            }

            // 扣除信用分
            log.debug("扣除用户 {} 的信用分: {}", userId, DEDUCT_SCORE_PER_VIOLATION);
            sysUserMapper.deductCredit(userId, DEDUCT_SCORE_PER_VIOLATION);

            // 更新状态为已驳回
            int rows = violationMapper.updateStatus(id, 3);
            log.info("更新影响行数: {}", rows);
        } catch (Exception e) {
            log.error("驳回操作失败: id={}, userId={}", id, userId, e);
            throw new RuntimeException("驳回失败", e);
        }
    }

    private Violation convertToViolation(Reservation reservation) {
        Violation violation = new Violation();
        violation.setUserId(reservation.getUserId());
        violation.setReservationId(reservation.getId());
        violation.setSeatId(reservation.getSeatId());
        violation.setRoomId(reservation.getRoomId());
        violation.setTimeSlot(reservation.getTimeSlot());
        violation.setReservationDate(reservation.getReservationDate());
        violation.setAppealStatus(0);
        return violation;
    }

    /**
     * 查询违规处理
     *
     * @param id 违规处理主键
     * @return 违规处理
     */
    @Override
    public Violation selectViolationById(Long id)
    {
        return violationMapper.selectViolationById(id);
    }

    /**
     * 查询违规处理列表
     *
     * @param violation 违规处理
     * @return 违规处理
     */
    @Override
    public List<Violation> selectViolationList(Violation violation)
    {
        return violationMapper.selectViolationList(violation);
    }

    /**
     * 新增违规处理
     *
     * @param violation 违规处理
     * @return 结果
     */
    @Override
    public int insertViolation(Violation violation)
    {
        return violationMapper.insertViolation(violation);
    }

    /**
     * 修改违规处理
     *
     * @param violation 违规处理
     * @return 结果
     */
    @Override
    public int updateViolation(Violation violation)
    {
        return violationMapper.updateViolation(violation);
    }

    /**
     * 批量删除违规处理
     *
     * @param ids 需要删除的违规处理主键
     * @return 结果
     */
    @Override
    public int deleteViolationByIds(Long[] ids)
    {
        return violationMapper.deleteViolationByIds(ids);
    }

    /**
     * 删除违规处理信息
     *
     * @param id 违规处理主键
     * @return 结果
     */
    @Override
    public int deleteViolationById(Long id)
    {
        return violationMapper.deleteViolationById(id);
    }
}
